# -*- coding: utf-8 -*-

import os
import yuantiangang
from lunisolar import lunisolar, greg_to_luni
from zh_lunisolar import zh_lunisolar, zh_number 
from datetime import date, datetime
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

def render(file, values):
    return template.render(os.path.join(os.path.dirname(__file__), 'templates', file), values)

def parse_date(s_date):
    try:
        d = datetime.strptime(s_date, "%Y/%m/%d")
        return d.date()
    except ValueError:
        return date.today()

class Home(webapp.RequestHandler):
    def get(self):
        self.response.out.write(render('index.html', {}))
    def post(self):
        birth_date = self.request.get('birth_date')
        birth_time = self.request.get('birth_time')
        self.redirect("/%s/%s" % (birth_date, birth_time))

def zh_weight(weight):
    if weight in range(21, 72):
        return "%s两%s钱" % (zh_number(weight/10), zh_number(weight%10))

def zh_time(time):
    return "%s时" % zh_number(time)
    
class Fortune(webapp.RequestHandler):
    def get(self, year, month, day, time):
        year, month, day, time = int(year), int(month), int(day), int(time)
        greg_birth = date(year, month, day)
        luni_birth = greg_to_luni(greg_birth)
        weight = yuantiangang.weight(luni_birth.year, luni_birth.month, luni_birth.day, time)
        critique, poem = yuantiangang.fortune(weight)
        self.response.out.write(render('fortune.html', { 'greg_birth': greg_birth.strftime("%Y年%m月%d日"),
                                                         'luni_birth': zh_lunisolar(luni_birth).__str__()+zh_time(time),
                                                         'weight': zh_weight(weight),
                                                         'critique': critique,
                                                         'poem': poem }))

def main():
    run_wsgi_app(application)

application = webapp.WSGIApplication([('/(\d{4})/(\d{1,2})/(\d{1,2})/(\d{1,2}).*', Fortune),
                                      ('/.*', Home)],
                                      debug=True)

if __name__ == "__main__":
    main()
